package codeRandomThoughts.Test216组合总和III;

import java.util.ArrayList;
import java.util.List;

public class Solution2 {
    private List<Integer> path = new ArrayList<>();
    private int pathSum = 0;
    private List<List<Integer>> result = new ArrayList<>();

    public List<List<Integer>> combinationSum3(int k, int n) {
        backtracking(k,n,1);
        return result;
    }

    public void backtracking(int k, int n, int startIndex) {
        //回溯终止条件
        if (path.size() == k && pathSum == n) {
            result.add(new ArrayList<>(path));
            return;
        }

        for (int i = startIndex; i <= (9 - (k - path.size()) + 1) && pathSum < n; i++) {
            pathSum += i;
            path.add(i);
            backtracking(k, n, i + 1);
            path.remove(path.size() - 1);
            pathSum -= i;
        }
    }
}
